﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;

namespace HttpService
{
    class Utils
    {
        /// <summary>
        /// 对?象??转?a换?成??json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonObject"> 需??要?a格?式??化??的??对?象?? </param>
        /// <returns> Json字??符??串?? </returns>
        public static string DataContractJsonSerialize<T>(T jsonObject)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            string json = null;
            using (MemoryStream ms = new MemoryStream()) //定??义??一??个?stream用??来???存??发???序??列?D化??之?后??的??内??容?Y
            {
                serializer.WriteObject(ms, jsonObject);
                json = Encoding.UTF8.GetString(ms.GetBuffer()); //将?stream读??取??成??一??个?字??符??串??形?式??的??数?y据Y，??并??且??返???回?
                ms.Close();
            }
            return json;
        }

        /// <summary>
        /// json字??符??串??转?a换?成??对?象??
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"> 要?a转?a换?成??对?象??的??json字??符??串?? </param>
        /// <returns></returns>
        public static T DataContractJsonDeserialize<T>(string json)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            T obj = default(T);
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                obj = (T)serializer.ReadObject(ms);
                ms.Close();
            }
            return obj;
        }

    }
}
